<!-- 费用编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="form.id > 0 ? '修改费用' : '新建费用'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="费用产生日期" prop="belongs_date">
        <el-date-picker
          v-model="form.belongs_date"
          type="date"
          style="width: 150px"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="分类" prop="cate_id">
        <el-select v-model="form.cate_id" filterable style="width: 200px">
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            :disabled="item.pid === 0"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="成本所属" prop="belongs">
        <el-radio-group v-model="form.belongs" @change="handleBelongsChange">
          <el-radio-button value="总部"> 总部 </el-radio-button>
          <el-radio-button value="区域">区域</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="区域" prop="area_id" v-if="form.belongs == '区域'">
        <el-select
          v-model="form.area_id"
          @change="getCompanyList"
          style="width: 200px"
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="车队"
        prop="company_id"
        v-if="form.belongs == '区域'"
      >
        <el-select v-model="form.company_id" style="width: 350px" filterable>
          <el-option
            v-for="item in companyList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="类型" prop="io_type">
        <el-radio-group v-model="form.io_type">
          <el-radio-button value="收入"> 收入 </el-radio-button>
          <el-radio-button value="支出">支出</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="金额" prop="amount">
        <el-input
          v-model="form.amount"
          @input="handleInput"
          style="width: 150px"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="备注">
        <el-input clearable v-model="form.remark" style="width: 400px" />
      </el-form-item>

      <el-form-item label="凭证" prop="images">
        <image-upload :limit="1000" v-model="form.images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import {
    updateCompanyIncomeExpense,
    pageCompanyIncomeExpenseCateTree,
    pageMyCompanyArea,
    pageCompanyList
  } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    status: 0,
    cate_id: '',
    io_type: '',
    area_id: '',
    company_id: '',
    amount: '',
    images: '',
    belongs_date: '',
    belongs: ''
  });

  const cateList = ref([]);
  const getCateList = () => {
    pageCompanyIncomeExpenseCateTree({})
      .then((res) => {
        cateList.value = res;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };
  /** 所属变更 */
  const handleBelongsChange = () => {
    if (form.belongs === '总部') {
      form.area_id = '';
      form.company_id = '';
    }
  };

  /** 车队列表 */
  const companyList = ref([]);
  const getCompanyList = () => {
    console.log('初始化车队列表');
    pageCompanyList({ area_id: form.area_id, page: 1, limit: 99999999 })
      .then((res) => {
        form.company_id = ''; // 重置车队选项
        companyList.value = res.list;
      })
      .catch((e) => {
        console.log(e);
      });
  };

  /** 区域列表 */
  const areaList = ref([]);
  const getAreaList = () => {
    pageMyCompanyArea({ limit: 99999999 })
      .then((res) => {
        res.list.shift();
        areaList.value = res.list;
      })
      .catch((e) => {
        console.log(e);
      });
  };
  const handleInput = () => {
    let value = form.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    form.amount = value;
  };

  /** 表单验证规则 */
  const rules = reactive({
    belongs: [
      {
        required: true,
        message: '请选择费用归属',
        type: 'string',
        trigger: 'blur'
      }
    ],

    io_type: [
      {
        required: true,
        message: '请选择收支类型',
        type: 'string',
        trigger: 'blur'
      }
    ],

    belongs_date: [
      {
        required: true,
        message: '请选择费用产生日期',
        type: 'string',
        trigger: 'blur'
      }
    ],

    amount: [
      {
        required: true,
        message: '请填写金额',
        type: 'string',
        trigger: 'blur'
      }
    ],
    cate_id: [
      {
        required: true,
        message: '请选择分类',
        type: 'integer',
        trigger: 'blur'
      }
    ],
    images: [
      {
        required: true,
        message: '请上传凭证',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    if (form.belongs === '区域') {
      if (form.area_id == '' || form.area_id == null || form.area_id == 0) {
        EleMessage.error('请选择区域');
        return;
      }
    }
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;

      updateCompanyIncomeExpense(form)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        getCateList();

        getAreaList();
        if (props.data) {
          assignFields({
            ...props.data
          });
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
